package com.authine.cloudpivot.ext.applicationservice;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapBuilder;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.Enum.InvoiceBusinessType;
import com.authine.cloudpivot.ext.Enum.InvoiceStatus;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.model.invoice.InvoiceApply;
import com.authine.cloudpivot.ext.dto.model.invoice.InvoiceDetail;
import com.authine.cloudpivot.ext.dto.query.InvoiceDetailQuery;
import com.authine.cloudpivot.ext.service.invoice.InvoiceDetailBillService;
import com.authine.cloudpivot.ext.service.invoice.InvoiceDetailService;
import com.authine.cloudpivot.ext.service.invoice.impl.InvoiceDetailBillServiceImpl;
import com.authine.cloudpivot.ext.service.invoice.impl.InvoiceDetailServiceImpl;
import com.authine.cloudpivot.ext.service.trade.TradeService;
import com.authine.cloudpivot.ext.service.trade.impl.TradeServiceImpl;
import com.authine.cloudpivot.ext.utils.*;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

@Slf4j
@Path("InvoiceDetailController")
public class InvoiceDetailController extends ApplicationService {

    InvoiceDetailBillService invoiceDetailBillService = new InvoiceDetailBillServiceImpl();
    InvoiceDetailService invoiceDetailService = new InvoiceDetailServiceImpl();
    TradeService tradeService = new TradeServiceImpl();


    @Path("deleteInvoiceDetail")
    @POST
    @Operation(summary = "平台采购发票申请单-待提交-修改-明细列表-删除", description = "平台采购发票申请单-待提交-修改-明细列表-删除，客户采购发票申请单-待提交-修改-明细列表-删除", tags = CUSTOM_SERVICE)
    public void deleteInvoiceDetail(Collection<String> invoiceDetailIds, Collection<String> invoiceIds){
       StringBuffer sql = new StringBuffer("select detail.* from ")
               .append(JdbcTemplateUtils.getTableName(ModelConst.T_INVOICE_DETAIL)).append(" as detail")
               .append(" left join ").append(JdbcTemplateUtils.getTableName(ModelConst.T_INVOICE_APPLY)).append(" as apply")
               .append(" on detail.invoice_apply_id = apply.id");
       MapBuilder<String, Object> mapBuilder = MapBuilder.create(new HashMap<>());
       if (!CollectionUtils.isEmpty(invoiceDetailIds)) {
           sql.append(" detail.id in (:invoiceDetailIds)");
          mapBuilder.put("invoiceDetailIds", invoiceDetailIds);
       }
        if (!CollectionUtils.isEmpty(invoiceIds)) {
            sql.append(" detail.invoice_apply_id in (:invoiceIds)");
            mapBuilder.put("invoiceIds", invoiceIds);
        }
        sql.append(" apply.statuss in (:statuss)");
        mapBuilder.put("statuss", Arrays.asList(InvoiceStatus.New.name(), InvoiceStatus.Returned.name()));
        List<InvoiceDetail> detailList = JdbcTemplateUtils.queryForPOJOList(sql.toString(), mapBuilder.build(), ModelConst.T_INVOICE_DETAIL, InvoiceDetail.class);
        if (CollectionUtils.isEmpty(detailList)) {
            return;
        }
        List<String> writeBackTrade = new ArrayList<>();
        invoiceDetailIds = new ArrayList<>();
        for (InvoiceDetail invoiceDetail : detailList) {
            BoServiceUtils.deleteBo( ModelConst.T_INVOICE_DETAIL, invoiceDetail.getId(), true);
            invoiceDetailIds.add(invoiceDetail.getId());

            SingleResponse<BO> response = BoServiceUtils.loadBo(invoiceDetail.getInvoice_apply_id(), ModelConst.T_INVOICE_APPLY);
            InvoiceApply invoiceApply = BeanUtil.mapToBean(response.getData().getData(), InvoiceApply.class, true);

            if (InvoiceBusinessType.Product.name().equals(invoiceApply.getBusiness_type())
                    || InvoiceBusinessType.RedProduct.name().equals(invoiceApply.getBusiness_type())) {
                writeBackTrade.add(invoiceDetail.getTrade_id());
            }
        }
        invoiceDetailBillService.remove(invoiceDetailIds);

        Set<String> invoiceApplyIds = detailList.stream().map(InvoiceDetail::getInvoice_apply_id).collect(Collectors.toSet());
        for (String invoiceApplyId : invoiceApplyIds) {
            InvoiceApply invoiceApplyEntity = JdbcTemplateUtils.builder(ModelConst.T_INVOICE_APPLY).selectField("*")
                    .eq("id", invoiceApplyId).queryForPOJO(InvoiceApply.class);
            //不删除结算单的时候，重新计算（修改发票明细的时候重新计算）
            if (null != invoiceApplyEntity) {
                //删除后，新的发票明细
                List<InvoiceDetail> invoiceDetailEntities = invoiceDetailService.listInvoiceDetail(InvoiceDetailQuery.builder().invoiceApplyIds(Collections.singleton(invoiceApplyId)).build());
                Assert.isTrue(!CollectionUtils.isEmpty(invoiceDetailEntities), "发票明细不可为空");

                BigDecimal sumAmount = CalculatorUtils.sum(invoiceDetailEntities, BiFunctionConst.invoiceDetailAmountFun);
                BigDecimal sumTotal = CalculatorUtils.sum(invoiceDetailEntities, BiFunctionConst.invoiceDetailTotalFun);
                BigDecimal sumTax = CalculatorUtils.sum(invoiceDetailEntities, BiFunctionConst.invoiceDetailTaxFun);

                invoiceApplyEntity.setTotal(sumTotal).setPrice_amount(sumAmount).setTax_amount(sumTax);
                BoServiceUtils.updateMainBo( ModelConst.T_INVOICE_APPLY, BeanUtil.beanToMap(invoiceApplyEntity));
            }
        }
        tradeService.writeBackAllowedInvoiceQuantity(writeBackTrade);

    }

}
